package com.bkhc.common.permissions.aspect;

import com.bkhc.common.annotation.ApiOperation;

import com.bkhc.common.entity.ApiInfo;
import com.bkhc.common.permissions.bean.RoleDetail;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.service.ApiInfoService;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Aspect
public class OpreationAspect {

    @Value("${spring.application.name}")
    public String appName;

    @Autowired
    private ApiInfoService apiInfoService;

    @Pointcut("@annotation(com.bkhc.common.annotation.ApiOperation)")
    public void pointcut(){

    }

    @Around("@annotation(apiOperation)")
    public Object checkPermissions(ProceedingJoinPoint joinPoint, ApiOperation apiOperation) throws Throwable {
       Object result = null;
        ApiInfo api = apiInfoService.getApiByCode(apiOperation.code());
        if(!"common".equals(api.getApiType())&&!"GG".equals(api.getApiType())){
            UserPermission permissions = CommonUtil.getCrruentUserPermission(appName);
            List<ApiInfo> apiInfoList = new ArrayList<>();

            List<RoleDetail> roleList = permissions.getRoles();
            if(CollectionUtils.isEmpty(roleList)){
                result = ResultJson.failure(ResultCode.FORBIDDEN);
                return result;
            }
            for(RoleDetail roleDetail:roleList){
                apiInfoList.addAll(roleDetail.getApiInfos());
            }
            List<ApiInfo> apis = apiInfoList.stream().filter(x -> x.getCode().equals(apiOperation.code())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(apis)){
                    result = joinPoint.proceed();
                return result;
            }else{
                result = ResultJson.failure(ResultCode.FORBIDDEN);
                return result;
            }
        }
        result = joinPoint.proceed();
        return result;
    }
}
